<?php

namespace app\admin\controller;

use Chumper\Zipper\Zipper;
use ParseCsv\Csv;
use think\App;
use think\facade\Cache;

class Export extends Base{

    protected $isSink = true;
    public function __construct(App $app = null){
        parent::__construct($app);
        set_time_limit(0);
        ini_set('memory_limit', '250M');
    }

    /**
     * 导出数据
     * @param string $mod       导出模型
     * @param string $where     导出条件
     * @param string $field     导出字段
     * @param string $order     排序
     * @return \think\Response
     * @throws \ReflectionException
     */
    public function export($mod='',$where='', $field ='*',$order=''){
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $header = [];
        $title = '';
        $prefix = config('database.prefix');
        $name = ucfirst($prefix.$mod);
        $class = new \ReflectionClass("\\app\\admin\\model\\$name");
        $instance  = $class->newInstanceArgs();
        $this->model = $instance;
        $where = $where?$this->_where($where):'';
        $counts = method_exists($instance,'counts');
        if ($counts){
            $result = $instance->counts($where);
        }else{
            $result = $instance->where($where)->count();
        }
        if(request()->isPost()){
            if(!$result){
                return $this->__e('没有符合条件的数据');
            }else{
                $params['mod'] = $mod;
                if($where){
                    $params['where1'] = $where;
                }
                if($field!='*'){
                    $params['field'] = $field;
                }
                $query = http_build_query($params);
                $host = request()->host();
                if($query){
                    $url = "http://{$host}/admin/export?{$query}";
                }else{
                    $url = "http://{$host}/admin/export";
                }
                return $this->__s('查询成功,本次可导出'.$result.'条数据',['url'=>$url]);
            }
        }
        $tableName = $instance->getTable();
        $fields = '';
        $_field  = [];
        $sql = "SELECT column_name as column_name,column_comment as column_comment,data_type as data_type  FROM information_schema.COLUMNS WHERE TABLE_NAME = '{$tableName}'";
        $sql1 = "SELECT table_name,table_comment FROM information_schema.TABLES WHERE TABLE_NAME='{$tableName}'";
        $_fields = $instance->query($sql);
        $_table = $instance->query($sql1);
        $header['sort']='排序';
        if(strpos($field,'*')===false){
            $field = explode(',',$field);
            foreach ($_fields as $v){
                if(in_array($v['column_name'],$field) && !key_exists($v['column_name'],$header)){
                    array_push($_field,$v['column_name']);
                    $fields .= ','.$v['column_name'];
                    if(empty($v['column_comment'])){
                        $comment =$v['column_name'];
                        $header[$v['column_name']] = $comment;
                        continue;
                    }
                    /*
                     else if(strpos($v['column_comment'],' ')!==false){
                        $column_comment = explode(' ',$v['column_comment']);
                        $header[$v['column_name']] = $column_comment[0];
                     }
                     */
                    if(strpos($v['column_comment'],':')!==false){
                        $column_comment = explode(':',$v['column_comment']);
                        $header[$v['column_name']] = $column_comment[0];
                    }else{
                        $header[$v['column_name']] = $v['column_comment'];
                    }
                }
            }
        }else{
            foreach ($_fields as $k => $v){
                if(strpos($v['column_comment'],':')!==false){
                    $column_comment = explode(':',$v['column_comment']);
                    $comment = $column_comment[0];
                }else{
                    $column_comment = explode(':',$v['column_comment']);
                    $comment = $column_comment[0];
                }
                $comment = $comment?$comment:$v['column_name'];
                $header[$v['column_name']] = $comment;
            }
        }
        $fields = $fields?substr($fields,1):'';
        $where1 = input('where1','');
        $result = $instance->export($where1,$fields,$order);
        if ($result) {      // 追加header
            $_temp = $result[0];
            if(count($_temp) != count($header)) {
                foreach ($_temp as $k => $v){
                    if(!isset($header[$k])){
                        $header[$k] = $k;
                    }
                }
            }
        }

        if($_table && $_table[0]['table_comment']){
            $title = $_table[0]['table_comment'];
        }
        $title = '导出'.($title ? $title.'_'.date('Ymd') : $name.'_'.date('Ymd'));
        $csv = new \ParseCsv\Csv();
        $csv->output("{$title}.csv", $result,$header);
        unset($result);
        ob_flush();
        flush();
    }


    public function export1($mod='',$where='', $field ='*'){
        $header = [];
        $title = '';
        $prefix = config('database.prefix');
        $name = ucfirst($prefix.$mod);
        $class = new \ReflectionClass("\\app\\admin\\model\\$name");
        $instance  = $class->newInstanceArgs();
        $this->model = $instance;
        $counts = method_exists($instance,'counts');
        if(request()->isPost()){
            $where = $where?$this->_where($where):'';
            if ($counts){
                $result = $instance->counts($where);
            }else{
                $result = $instance->where($where)->count();
            }
            if(!$result){
                return $this->__e('没有符合条件的数据');
            }else{
                $params['mod'] = $mod;
                if($where){
                    $params['where1'] = $where;
                }
                if($field!='*'){
                    $params['field'] = $field;
                }
                $query = http_build_query($params);
                $host = request()->host();
                $tmp = explode('::',__METHOD__);
                $url = "http://{$host}/admin/".end($tmp)."?{$query}";
                return $this->__s('查询成功,本次可导出'.$result.'条数据',['url'=>$url]);
            }
        } else {
            $where =input('where1');
            if ($counts){
                $result = $instance->counts($where);
            }else{
                $result = $instance->where($where)->count();
            }
        }
        $tableName = $instance->getTable();
        $fields = '';
        $_field  = [];
        $sql = "SELECT column_name as column_name,column_comment as column_comment,data_type as data_type  FROM information_schema.COLUMNS WHERE TABLE_NAME = '{$tableName}'";
        $sql1 = "SELECT table_name,table_comment FROM information_schema.TABLES WHERE TABLE_NAME='{$tableName}'";
        $_fields = $instance->query($sql);
        $_table = $instance->query($sql1);
        $header['sort']='排序';

        if(strpos($field,'*')===false){
            $field = explode(',',$field);
            foreach ($_fields as $v){
                if(in_array($v['column_name'],$field) && !key_exists($v['column_name'],$header)){
                    array_push($_field,$v['column_name']);
                    $fields .= ','.$v['column_name'];
                    if(empty($v['column_comment'])){
                        $comment =$v['column_name'];
                        $header[$v['column_name']] = $comment;
                        continue;
                    }
                    /*
                     else if(strpos($v['column_comment'],' ')!==false){
                        $column_comment = explode(' ',$v['column_comment']);
                        $header[$v['column_name']] = $column_comment[0];
                     }
                     */
                    if(strpos($v['column_comment'],':')!==false){
                        $column_comment = explode(':',$v['column_comment']);
                        $header[$v['column_name']] = $column_comment[0];
                    }else{
                        $header[$v['column_name']] = $v['column_comment'];
                    }
                }
            }
        }else{
            foreach ($_fields as $k => $v){
                if(strpos($v['column_comment'],':')!==false){
                    $column_comment = explode(':',$v['column_comment']);
                    $comment = $column_comment[0];
                }else{
                    $column_comment = explode(':',$v['column_comment']);
                    $comment = $column_comment[0];
                }
                $comment = $comment?$comment:$v['column_name'];
                $header[$v['column_name']] = $comment;
            }
        }
        $limit = 10000;
        $page = ceil($result / $limit);
        $i = 1;
        $headers = [];
        $zipper = new Zipper();
        if($_table && $_table[0]['table_comment']){
            $title = $_table[0]['table_comment'];
        }
        $folder = '../data/zip/';
        $zip = $folder.$title.'.zip';
        $zipper->make($zip);
        $files = [
            $zip
        ];
        while ($i <= $page){
            $result_list = $instance->exportToZip($where,$limit,$i,$headers);
            if($result_list){
                $path = $folder.'导出用户信息'.date('Ymd',time()).'('.$i.')'.'.csv';
                $csv = new Csv();
                $csv->save($path,$result_list,false,$headers);
                $zipper->add($path);
                array_push($files,$path);
                $i++;
            }
        }
        $zipper->close();
        Cache::rm('company_list');
        if(is_file($zip)){
            $file = fopen ($zip, "rb");
            $size = filesize ($zip);
            foreach ($files as $v){
                if(is_file($v)){
                    unlink($v);
                }
            }
            Header ("Content-type: application/octet-stream");
            Header ("Accept-Ranges: bytes");
            Header ("Accept-Length: {$size}");
            Header ("Content-Disposition: attachment; filename=".$title.'.zip');
            echo fread ($file,$size);
            fclose ($file);
            exit ();
        }
    }

    /**
     * @param string $mod
     * @param string $field
     * @param string $method
     * @param array $where
     * @param string $limit
     * @param string $order
     * @return \think\Response
     * @throws \ReflectionException
     */
    public function export2($mod='',$field='*',$method='',$where=[],$limit='',$order=''){
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $header = [];
        $prefix = config('database.prefix');
        $name = ucfirst($prefix.$mod);
        $class = new \ReflectionClass("\\app\\admin\\model\\$name");
        $instance  = $class->newInstanceArgs();
        $this->model = $instance;
        $where = $where?$this->_where($where):'';
        $counts = method_exists($instance,'counts');
        if ($counts){
            $result = $instance->counts($where);
        }else{
            $result = $instance->where($where)->count();
        }
        if(request()->isPost()){
            if(!$result){
                return $this->__e('没有符合条件的数据');
            }else{
                $params['mod'] = $mod;
                $params['method'] = $method;
                $params['limit'] = $limit;
                if($where){
                    $params['where1'] = $where;
                }
                if($field!='*'){
                    $params['field'] = $field;
                }
                $query = http_build_query($params);
                $host = request()->host();
                if($query){
                    $url = "http://{$host}/admin/export2?{$query}";
                }else{
                    $url = "http://{$host}/admin/export2";
                }
                return $this->__s('查询成功,本次可导出'.$result.'条数据',['url'=>$url]);
            }
        }
        $fields = $title = '';
        $header['sort']='排序';
        $fields = $fields?substr($fields,1):'';
        $where1 = input('where1','');
        $result = $instance->export($where1,$fields,$order,$header);
        $title = '导出'.($title ? $title.'_'.date('Ymd') : $name.'_'.date('Ymd'));
        $csv = new \ParseCsv\Csv();
        $csv->output("{$title}.csv", $result,$header);
        unset($result);
        ob_flush();
        flush();
    }

    /**
     * @param string $mod
     * @param string $field
     * @param string $method
     * @param array $where
     * @param string $limit
     * @param string $order
     * @param string $title
     * @return \think\Response
     * @throws \ReflectionException
     */
    public function export3($mod='',$field='*',$method='export',$where=[],$limit='',$order='',$title='导出数据'){
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $header = [];
        $prefix = config('database.prefix');
        $name = ucfirst($prefix.$mod);
        $class = new \ReflectionClass("\\app\\admin\\model\\$name");
        $instance  = $class->newInstanceArgs();
        $this->model = $instance;
        $where = $where?$this->_where($where):'';
        $counts = method_exists($instance,'counts');
        $order = $order?$this->_order($order):'';
        if ($counts){
            $result = $instance->counts($where);
        }else{
            $result = $instance->where($where)->count();
        }
        if(request()->isPost()){
            if(!$result){
                return $this->__e('没有符合条件的数据');
            }else{
                $params = request()->param();
                $query = http_build_query($params);
                $host = request()->host();
                if($query){
                    $url = "http://{$host}/admin/export3?{$query}";
                }else{
                    $url = "http://{$host}/admin/export3";
                }
                return $this->__s('查询成功,本次可导出'.$result.'条数据',['url'=>$url]);
            }
        }
        $_result = $instance->$method($where,$order,$header);
        if($_result){
            $title = '导出'.($title ? $title.'_'.date('Ymd') : $name.'_'.date('Ymd'));
            $csv = new \ParseCsv\Csv();
//            p($header);
//            p($_result);die;
            $csv->output("{$title}.csv", $_result,$header);
            ob_flush();
            flush();
        }else{
            exit('没有导出数据');
        }
    }
}
